<template>
  <el-dialog title="编辑机构" :visible.sync="dialogVisible" width="700px" :before-close="handleCancel">
    <organize-form isEdit :details="details" @save="handleSave" @cancel="handleCancel" />
  </el-dialog>
</template>

<script>
import { getAgencyDetail, editAgency } from '@/api/organize'
import OrganizeForm from './organizeForm'
import { params } from './options.js'

export default {
  name: 'OrganizeEdit',
  data() {
    return {
      dialogVisible: false,
      details: { ...params }
    }
  },

  props: {
    dialog: {
      type: Boolean,
      default: false
    },
    editId: {
      type: Number,
      default: 0
    }
  },

  watch: {
    dialog(boolean) {
      this.dialogVisible = boolean
      if (boolean && this.editId) {
        this.handleGetAgencyDetail()
      }
    }
  },

  methods: {
    // 机构详情
    handleGetAgencyDetail() {
      const id = this.editId
      getAgencyDetail({ id })
        .then(({ data = {} }) => {
          const { id: agencyId, type, agencyName, provinceId, cityId, areaId, description = '', schoolId = '', schoolName, tagIds, recommend } = data
          this.details = {
            type,
            agencyId,
            agencyName,
            areaId: [provinceId, cityId, Number(areaId)],
            description,
            schoolId: '' + schoolId,
            schoolName,
            tagIds,
            recommend: recommend.toString()
          }
        })
        .catch(() => {
          this.initDetails()
        })
    },

    // 编辑机构
    handleSave(params) {
      editAgency(params)
        .then(res => {
          this.dialogVisible = false
          this.$message({
            message: '编辑机构成功！',
            type: 'success'
          })
          this.$emit('edit')
        })
        .catch(() => {
          this.$emit('cancel')
        })
    },

    handleCancel() {
      this.$emit('cancel')
    },

    initDetails() {
      this.details = { ...params }
    }
  },

  components: {
    OrganizeForm
  }
}
</script>

